import { AppDataSource } from "../../data-source"
import { User } from "../../entity/User";
import jsonwebtoken = require('jsonwebtoken')
import bcrypt = require('bcrypt')
import { expressjwt, Request as JWTRequest } from "express-jwt";
import express = require('express')

const router = express.Router()
const UserRepository = AppDataSource.getRepository(User)

// $route  POST api/users/register
// @desc   返回 json 数据
// @access public
router.post('/register', async (req, res) => {
    await UserRepository.findOneBy({
        name: req.body.name
    })
    .then(async user => {
        if (user) {
            return res.status(400).json({
                msg: '用户名已被注册！'
            })
        } else {
            let newUser = new User()

            const { name, email } = req.body
            Object.assign(newUser, { name, email })

            newUser.avatar = 'TODO'
            newUser.password = bcrypt.hashSync(req.body.password, 10)

            await UserRepository.save(newUser)
                .then(user => res.json({
                    msg: '注册成功！'
                }))
                .catch(err => console.log(err))
        }
    })
})

// $route  POST api/users/login
// @desc   返回 token
// @access public
router.post('/login', async (req, res) => {
    const { name, password } = req.body
    await UserRepository.findOneBy({
        name
    })
    .then(user => {
        if (!user) {
            return res.status(404).json({
                msg: '用户不存在！'
            })
        } else {
            if (bcrypt.compareSync(password, user.password)) {
                const rule = { 
                    id: user.id,
                    name: user.name,
                    avatar: user.avatar,
                }
                // 把 id 和 name 作为信息 secret 为 key 存储到 token 中去
                jsonwebtoken.sign(rule, 'secret', { expiresIn: 3600 }, (err, token) => {
                    if (err) throw err
                    res.json({
                        msg: 'Success!',
                        token: 'Bearer ' + token
                    })
                })
            } else {
                res.status(400).json({
                    msg: '密码错误！'
                })
            }
        }
    })
})

// $route  POST api/users/current
// @desc   返回 json 对象
// @access Private
router.get('/current', expressjwt({ secret: 'secret', algorithms: ['HS256'] }), async (req, res) => {
    if (req.auth) {
        let user = await UserRepository.findOneBy({
            id: req.auth.id
        })
        res.send({
            id: user.id,
            name: user.name,
        })
    } else {
        res.status(401)
    }
})

router.post('/clear', async(req, res) => {
    await UserRepository.clear()
    res.send('data sheets are all clear.')
})

router.get('/test', (req, res) => {
    console.log('ok')
    res.json({
        msg: 'ok'
    })
})

module.exports = router
